package com.eastmelon.blog.controller;

import java.io.IOException;
import java.security.NoSuchAlgorithmException;
import java.util.Date;

import javax.annotation.Resource;

import org.apache.commons.io.FilenameUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import com.eastmelon.blog.entity.User;
import com.eastmelon.blog.service.IndexService;
import com.eastmelon.blog.service.UserService;
import com.eastmelon.blog.util.SecurityUtil;

@Controller("UserController")
@RequestMapping("/back/user")
public class UserController {
	@Resource
	private UserService userService;
	@Resource(name="indexService")
	private IndexService indexService;

	@RequestMapping("/userInfor")
	public String userInfor(Model model) {
		User user = userService.get(1);
		model.addAttribute("user", user);
		return "back/user/userInfor";
	}

	@RequestMapping("/updateUser")
	public String saveUser(Model model, User user) throws NoSuchAlgorithmException {
		if(!"".equals(user.getPassword()) && user.getPassword()!=null){
			user.setPassword(SecurityUtil.md5(user.getUsername(), user.getPassword()));
		}
		userService.update(user);
		indexService.createNav();
		return "back/user/userInfor";
	}

	@RequestMapping("/uploadImage")
	public String uploadImage(@RequestParam MultipartFile userImage, User user)
			throws IOException {
		// 获取文件扩展名
		String exn = FilenameUtils.getExtension(userImage.getOriginalFilename());
		String imageName = String.valueOf(new Date().getTime()) + "." + exn;
		String oldImageName = userService.getImageName(user.getId());
		user.setImageName(imageName);
		userService.uploadUserIamge(user, userImage.getInputStream(), oldImageName);
		indexService.createHeader();
		return "redirect:/back/user/userInfor.do";
	}

}
